<template>
<div class="ivu-card ivu-card-bordered ivu-card-dis-hover">
  <div class="ivu-card-head"><p>创建分类</p></div>
  <div class="ivu-card-body">
    <iForm ref="formRef" :model="formModel" :rules="rules" :label-width="100">
      <FormItem prop="name" label="分类名称：">
        <Input v-model="formModel.name" placeholder="分类名称"/>
      </FormItem>

      <FormItem prop="status" label="分类状态">
        <i-select v-model="formModel.status">
          <i-option v-for="(vStatus, kStatus) in config['common_status']" :value="kStatus" :key="kStatus">{{ vStatus }}</i-option>
        </i-select>
      </FormItem>

      <FormItem>
        <Button type="primary" :loading="submitLoading" @click="handleSubmit">创建</Button>
        <Button type="ghost" @click="$router.go(-1);">返回</Button>
      </FormItem>
    </iForm>
  </div>
</div>
</template>

<script>
import qs from 'qs';
import { Form, Button, Input, Select, Option, Message } from 'iview';
import auth from '@/utils/auth';
import ajaxiView from '@/utils/ajaxiView';
import apiConfig from '@/utils/apiConfig';

export default {
  components: {
    [Form.name]: Form,
    [Form.Item.name]: Form.Item,
    [Input.name]: Input,
    [Select.name]: Select,
    [Option.name]: Option,
    [Button.name]: Button
  },
  data() {
    return {
      config: {},
      token: auth.getToken(),
      formModel: {
        name: '',
        status: 0
      },
      submitLoading: false,
      rules: {
        name: [
          {required: true, message: '分类名称不能为空!', trigger: 'blur'}
        ],
        status: [
          {type: 'number', required: true, message: '请选择分类状态!', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    _initialize() {
      var _this = this;
      ajaxiView.get('/products/class/'+_this.$route.params.products_class_id+'?token='+_this.token).then(function(data) {
        if(data !== false) {
          _this.formModel.name = data.products_class.name;
          _this.formModel.status = data.products_class.status*1;
        }
      });
    },
    handleSubmit() {
      var _this = this;
      _this.$refs.formRef.validate((valid) => {
        _this.submitLoading = true;

        if(valid) {
          ajaxiView.put('/products/class/'+_this.$route.params.products_class_id+'?token='+_this.token, qs.stringify(_this.formModel)).then(function(data) {
            if(data !== false) {
              Message.success({
                content: data.msg,
                onClose: function() {
                  _this.$router.push({ name: 'shopProductsClassIndex' });
                }
              });
            }
          });
        }

        _this.submitLoading = false;
      });
    }
  },
  mounted() {
    var _this = this;
    apiConfig.getItem().then(function(value) {
      _this.config = value;
      _this._initialize();
    });
  }
}
</script>

<style>
</style>